package utils.linkedList;

import lombok.Data;

import java.util.List;

@Data
//带头结点的单向链表
public class LinkedList {
    private ListNode head;
    private int length;

    //具有头结点的链表
    public LinkedList(){
        head = new ListNode(0,null);
        length = 0;
    }

    public ListNode getHead(){return this.head;}

    public ListNode getLast(){
        return inquireListNode(length);
    }


    public int getLength(){return this.length;}

    //初始化链表
    public ListNode initLinkedList(int[] val){
        if(val==null){
            return null;
        }
        this.length = val.length;
        ListNode last = head;
        for (int j : val) {
            ListNode node = new ListNode(j, null);
            last.next = node;
            last = node;
        }
        return head;
    }

    public ListNode initLinkedList(List<Integer> list){
        if (list==null){
            return null;
        }
        Integer[] integers = list.toArray(new Integer[0]);
        int[] ints = new int[integers.length];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = integers[i];
        }
        return this.initLinkedList(ints);
    }

    //在链尾增加一个结点
    public void addLast(ListNode node){
        insertListNode(node,length);
    }

    //在链头增加一个结点
    public void addHead(ListNode node) {
        insertListNode(node,0);
    }

    //插入第k个结点的后面
    public boolean insertListNode(ListNode node,int k){
        if (k<0||k>this.length){
            return false;
        }
        ListNode listNode = head;
        for (int i = 0; i < k; i++) {
            listNode = listNode.next;
        }
        node.next = listNode.next;
        listNode.next = node;
        this.length++;
        return true;
    }

    //删除第k个结点
    public boolean deleteListNode(int k){
        if (k>this.length || k<=0){
            return false;
        }
        ListNode node = head;
        for (int i = 0; i < k; i++) {
            node = node.next;
        }
        node.next = node.next.next;
        this.length--;
        return false;
    }

    //得到第k个结点
    public ListNode inquireListNode(int k){
        if (k<=0||k>length){
            return null;
        }
        ListNode node = head;
        for (int i=0;i<k;i++){
            node = node.next;
        }
        return node;
    }

    //遍历
    public void travelLinkedList(){
        ListNode node = this.head;
        System.out.println("链表长度："+this.length);
        while (node.next!=null){
            node = node.next;
            System.out.print(node.val+" ");
        }
        System.out.println();
    }

}
